// pages/other//redbag/index.js
const Page = require('../../../utils/ald-stat.js').Page;
const app = getApp();
let interstitialAd = null;
const util = require('../../../utils/throttle.js');
const innerAudioContext = wx.createInnerAudioContext();
let videoAd = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    day: [
      "第一天", "第二天", "第三天", "第四天", "第五天", "第六天", "第七天",
    ],
    record: '',
    clickedfail: true,
    clickedsuc: true,
    tryfail: true,
    trysuc: true,
    redbag: true,
    sevenbag: true,
    ad_id: '',
    count: '',
    today_reward: '',
    total_reward: '',
    list: '',
    ad_data: '',
    erweima: '',
    number: '',
    block: "",
    seat: '',
    ishaveluck: true,
    flow:false,
    todaysuc:true,
    is_step:false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this;
    wx.showLoading({
      title: '加载中',
    })
    if (options.home == 1) {
      var object = {
        unionid: wx.getStorageSync('openid'),
        type: 21
      }
      var signs = app.sort_ASCII(object)
      wx.request({
        url: app.globalData.new_url + '/redpacket/Theme/activity_reward',
        data: {
          unionid: wx.getStorageSync('openid'),
          type: 21,
          sign: signs
        },
        method: 'POST',
        header: {
          'Cache-Control': 'max-age=60,public', //60秒
        },
        success: function (res) {
          console.log(res)
          if(res.data.code===200){
            that.setData({
              trysuc: false,
              clickedsuc: true,
              number: res.data.tc_reward,
              block:7
            })
          }
        }
      })
    }
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-f5bc8f11386e1481'
      })
      interstitialAd.onError((err) => {
        console.log('onError event emit', err)
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-5e84aa2ba6c0de6e'
      });
      videoAd.load();
      videoAd.onError(function(res) {
        console.log(101, res)
        if (res.errMsg == 'no advertisement' || res.errMsg == 'no ad unit id' || res.errCode == 1004) {
          that.setData({
            ishaveluck: false,
          })
        }
      })
      videoAd.onClose((status) => {
        if (status && status.isEnded) {
          that.music();
          var obj = {
            unionid: wx.getStorageSync('openid'),
            block: that.data.block
          }
          var sign = app.sort_ASCII(obj)
          wx.request({
            url: app.globalData.new_url + '/adauth/Adv/incentive',
            data: {
              unionid: wx.getStorageSync('openid'),
              block: that.data.block,
              sign: sign
            },
            method: "POST",
            header: {
              'Cache-Control': 'max-age=60,public', //60秒
            },
            success: function(res) {
              console.log('视频奖励', res)
              that.setData({
                sevenbag: true,
                redbag: true,
                clickedsuc: true,
                trysuc: false,
                number: res.data.content,
              })
            }
          })
        } else {
          return
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const that = this;
    if (that.data.erweima == 3) {
      that.setData({
        clickedsuc: true,
        trysuc: false,
      })
      that.data.erweima = 0
    } else if (that.data.erweima == 4) {
      that.setData({
        clickedfail: true,
        tryfail: false,
      })
      that.data.erweima = 0
    }
    if (app.globalData.scene === 1038 && that.data.flow) {
      var object = {
        unionid: wx.getStorageSync('openid'),
        type: 2,
        ad_id: that.data.ad_data.ad_id,
        plate: that.data.plate,
      }
      var signs = app.sort_ASCII(object)
      wx.request({
        url: app.globalData.new_url + '/adauth/Adv/back_adv',
        data: {
          unionid: wx.getStorageSync('openid'),
          type: 2,
          ad_id: that.data.ad_data.ad_id,
          plate: that.data.plate,
          sign: signs
        },
        method: "POST",
        header: {
          'Cache-Control': 'max-age=60,public', //60秒
        },
        success: function(res) {
          console.log(res.data.msg, res)
          app.globalData.scene = 1001;
          that.data.erweima = 0;
          if (res.data.code == 200) {
            that.setData({
              number: res.data.content,
              trysuc: false,
              clickedsuc:true,
            })
          } else {
            that.setData({
              tryfail: false,
              clickedfail: true
            })
          }
        }
      })
    }
    var obj = {
      unionid: wx.getStorageSync('openid')
    }
    var sign = app.sort_ASCII(obj)
    wx.request({
      url: app.globalData.new_url + '/redpacket/Theme/index',
      data: {
        unionid: wx.getStorageSync('openid'),
        sign: sign
      },
      method: "POST",
      header: {
        'Cache-Control': 'max-age=60,public', //60秒
      },
      success: function(res) {
        console.log(res)
        wx.hideLoading();
        that.setData({
          is_step: res.data.content.is_step,
          count: res.data.content.count,
          total_reward: res.data.content.total_reward,
          today_reward: res.data.content.today_reward,
          list: res.data.content.list,
        })
        if (res.data.content.ad) {
          that.setData({
            ad_id: res.data.content.ad.ad_id
          })
        }else{
          that.setData({
            ad_id: false
          })
        }
      }
    })
  },
  onReady: function() {
    const that = this;
    var obj = {
      type: 2
    }
    var sign = app.sort_ASCII(obj)
    wx.request({
      url: app.globalData.new_url + '/redpacket/Theme/red_win_record',
      data: {
        type: 2,
        sign: sign
      },
      method: "POST",
      header: {
        'Cache-Control': 'max-age=60,public', //60秒
      },
      success: function(res) {
        console.log(res)
        that.setData({
          record: res.data.content
        })
      }
    })

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    app.globalData.scene = 1001;
  },
  music: function() {
    innerAudioContext.src = 'https://www.mnancheng.com/Public/home/bj_music.mp3'
    innerAudioContext.play()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    let that = this;
    wx.showNavigationBarLoading() //在标题栏中显示加载
    that.onShow(); // 刷新页面
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  goindex: function () {
    wx.switchTab({
      url: '/pages/tarbar/index/index',
    })
  },
  todaybag: function(e) {
    const that = this;
    that.setData({
      block: 8,
    })
    var is_ad = 1
    var form_id = e.detail.formId;
    var obj = {
      unionid: wx.getStorageSync('openid'),
      formid: form_id,
      block: 8,
      is_ad: is_ad
    }
    var sign = app.sort_ASCII(obj)
    wx.request({
      url: app.globalData.new_url + '/adauth/Adv/get_formid',
      data: {
        unionid: wx.getStorageSync('openid'),
        formid: form_id,
        block: 8,
        is_ad: is_ad,
        sign: sign
      },
      method: "POST",
      header: {
        'Cache-Control': 'max-age=60,public', //60秒
      },
      success: function(res) {
        console.log(res)
        if (that.data.is_step){
          that.setData({
            todaysuc: false,
            number: res.data.content
          },()=>{
            if (interstitialAd) {
              interstitialAd.show().catch((err) => {
                console.error(err)
              })
            }
          })
        }else{
          that.setData({
            clickedsuc: true,
            trysuc: false,
            number: res.data.content
          },()=>{
            if (interstitialAd) {
              interstitialAd.show().catch((err) => {
                console.error(err)
              })
            }
          })
        }
      }
    })
  },
  navigateTovideo: util.throttle(function(e) {
    const that = this;
    var block = e.target.dataset.block
    that.setData({
      block: block
    })
    videoAd.show().catch(err => {
      videoAd.load().then(() => {
        videoAd.show();
      })
    })
  }, 1500),
  continueplay: function() {
    const that = this;
    if (that.data.seat == 9) {
      that.setData({
        sevenbag: false,
        tryfail: true,
        clickedfail: false
      })
    } else {
      that.setData({
        redbag: false,
        tryfail: true,
        clickedfail: false
      })
    }
  },
  luckbags: util.throttle(function(e) {
    const that = this;
    var block = e.target.dataset.block;
    that.setData({
      block: block
    })
    if (that.data.ad_id) {
      that.data.seat = e.target.dataset.seat;
      const plate = e.target.dataset.plate;
      that.data.plate = plate;
      var ad_id = e.target.dataset.id;
      var obj = {
        unionid: wx.getStorageSync('openid'),
        ad_id: ad_id,
        block: block
      }
      var sign = app.sort_ASCII(obj)
      wx.request({
        url: app.globalData.new_url + '/adauth/Adv/get_ad',
        data: {
          unionid: wx.getStorageSync('openid'),
          block: block,
          ad_id: ad_id,
          sign: sign
        },
        method: "POST",
        header: {
          'Cache-Control': 'max-age=60,public', //60秒
        },
        success: function(res) {
          console.log(res)
          that.setData({
            ad_data: res.data.content,
          })
          if (res.data.content.way == 1) {
            if (block == 6) {
              that.setData({
                redbag: false,
              })
            } else {
              that.setData({
                sevenbag: false
              })
            }
          } else {
            var ad_id = res.data.content.ad_id
            wx.navigateTo({
              url: '../../other/erweima/index?ad_id=' + ad_id + '&&plate=' + plate,
            })
          }
        }
      })
    } else if (that.data.ishaveluck) {
      that.setData({
        sevenbag: false
      })
    } else {
      var obj = {
        unionid: wx.getStorageSync('openid'),
        block: block
      }
      var sign = app.sort_ASCII(obj)
      wx.request({
        url: app.globalData.new_url + '/adauth/Adv/incentive',
        data: {
          unionid: wx.getStorageSync('openid'),
          block: block,
          sign: sign
        },
        method: "POST",
        header: {
          'Cache-Control': 'max-age=60,public', //60秒
        },
        success: function(res) {
          console.log('第7天直接奖励', res)
          that.setData({
            clickedsuc: true,
            trysuc: false,
            number: res.data.content,
          })
        }
      })
    }
  }, 1500),
  navigateToAd: function(e) {
    const that = this;
    that.data.seat = e.target.dataset.seat;
    const plate = e.target.dataset.plate;
    that.data.plate = plate;
    const ad_data = that.data.ad_data;
    const ad_id = ad_data.ad_id;
    var obj = {
      unionid: wx.getStorageSync('openid'),
      ad_id: ad_id,
      type: 1,
      plate: plate
    }
    var sign = app.sort_ASCII(obj)
    if (ad_data.way == 1) {
      wx.navigateToMiniProgram({
        appId: ad_data.appid,
        path: ad_data.path,
        envVersion: 'develop',
        success(res) {
          wx.request({
            url: app.globalData.new_url + '/adauth/Adv/back_adv',
            data: {
              unionid: wx.getStorageSync('openid'),
              type: 1,
              ad_id: ad_id,
              plate: plate,
              sign: sign
            },
            method: "POST",
            header: {
              'content-type': 'application/json'
            },
            success: function(res) {
              console.log('跳转成功', res)
              that.setData({
                sevenbag: true,
                redbag: true,
              })
              that.data.flow = true;
            }
          })
        }
      })
    } else {
      wx.navigateTo({
        url: '../../other/erweima/index?ad_id=' + ad_id + '&&plate=' + plate,
      })
      that.setData({
        sevenbag: true,
        redbag: true,
      })
    }
  },
  sharefriend: function() {
    wx.navigateTo({
      url: '/pages/other/redshare/index',
    })
  },
  gotocash: function() {
    wx.navigateTo({
      url: '/pages/other/money/index',
    })
  },
  hideHandle: function() {
    const that = this;
    that.setData({
      tryfail: true,
      clickedfail: false,
      redbag: true,
      sevenbag: true,
    })
  },
  hidesuc: function() {
    const that = this;
    that.setData({
      trysuc: true,
      clickedsuc: false,
    },()=>{
      if (interstitialAd) {
        interstitialAd.show().catch((err) => {
          console.error(err)
        })
      }
    })
    that.data.flow = false;
    that.onShow();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var openid = wx.getStorageSync('openid')
    return {
      title: '步数换好礼，我正在用步数免费领礼品，你也快来！',
      imageUrl: '../../../imgs/openshare.jpg',
      path: '/pages/tarbar/index/index?openid=' + openid + '&&jx=55'
    }
  },
})